<template>
  <div class="container">
    <button class="exercise-btn" @click="showExercisePanel">我的收藏</button>
  </div>

  <el-dialog
    v-model="visiblePanel"
    title="我的收藏本"
    width="800px"
    :close-on-click-modal="false"
    @close="closePanel"
  >
  <div class="search-container">
      <el-select
        v-model="selectedPrompt"
        filterable
        clearable
        placeholder="请选择或输入prompt"
        class="prompt-select"
      >
        <el-option
          v-for="item in promptOptions"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      <!-- <el-button
        type="primary"
        @click="searchByPrompt"
        class="search-btn"
      >
        按prompt搜寻
      </el-button> -->
    </div>
    <el-tabs v-model="activeTab" type="card" @tab-change="handleTabChange">

      <el-tab-pane label="选择题" name="choice">
        <div class="question-list">
          <div
            v-for="(question, index) in filteredChoiceQuestions"
            :key="question.id"
            class="question-item"
          >
            <div class="question-header">
              <span class="question-index">{{ index + 1 }}.</span>
              <span>{{ question.header }}</span>
            </div>
            <div class="question-options">
              <div>A. {{ question.choiceA }}</div>
              <div>B. {{ question.choiceB }}</div>
              <div>C. {{ question.choiceC }}</div>
              <div>D. {{ question.choiceD }}</div>
            </div>
            <div class="question-answer">正确答案: {{ question.rightanswer }}</div>
            <div class="question-actions">
              <!-- <el-button type="primary" size="small" @click="showNotDeveloped">重新练习</el-button>
              <el-button type="success" size="small" @click="showNotDeveloped">标记为已掌握</el-button> -->
              <el-button type="danger" size="small" @click="deletechoice(question)">删除</el-button>
            </div>
          </div>
          <div v-if="filteredChoiceQuestions.length === 0" class="empty-tip">
            暂无选择题错题记录
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="填空题" name="answer">
        <div class="question-list">
          <div
            v-for="(question, index) in filteredAnswerQuestions"
            :key="question.id"
            class="question-item"
          >
            <div class="question-header">
              <span class="question-index">{{ index + 1 }}.</span>
              <span>{{ question.header }}</span>
            </div>
            <div class="question-answer">正确答案: {{ question.rightanswer }}</div>
            <div class="question-actions">
              <!-- <el-button type="primary" size="small" @click="showNotDeveloped">重新练习</el-button>
              <el-button type="success" size="small" @click="showNotDeveloped">标记为已掌握</el-button> -->
              <el-button type="danger" size="small" @click="deletanswer(question)">删除</el-button>
            </div>
          </div>
          <div v-if="filteredAnswerQuestions.length === 0" class="empty-tip">
            暂无填空题错题记录
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- <template #footer>
      <el-button @click="closePanel">关闭</el-button>
    </template> -->
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { choiceQ, answerQ,deleteMyWAnswerQ,deleteMyWChoiceQ } from '@/api/modules/axiosApi'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/userStore'
import {findpromptC} from '@/api/modules/axiosApi'
import {findpromptA} from '@/api/modules/axiosApi'
import {findanswerquestionprompt} from '@/api/modules/axiosApi'
import {findchoicequestionprompt} from '@/api/modules/axiosApi'
import { computed } from 'vue'
const visiblePanel = ref(false)
const activeTab = ref('choice')
const choiceQuestions = ref([])
const answerQuestions = ref([])
const userStore = useUserStore()
// const choiceRes=ref([])
// const answerRes=ref([])
const status = 0
const selectedPrompt = ref('')
const promptOptions = ref([])

const filteredChoiceQuestions = computed(() => {
  if (!selectedPrompt.value) {
    return choiceQuestions.value // 未选择 prompt，返回全部
  }
  return choiceQuestions.value.filter(
    q => q.prompt === selectedPrompt.value
  )
})

// 计算属性：根据 selectedPrompt 过滤填空题
const filteredAnswerQuestions = computed(() => {
  if (!selectedPrompt.value) {
    return answerQuestions.value // 未选择 prompt，返回全部
  }
  return answerQuestions.value.filter(
    q => q.prompt === selectedPrompt.value
  )
})
const showExercisePanel = async () => {
  const user_id=userStore.user.id
  visiblePanel.value = true
  console.log(user_id,status);


  try {
    // 获取选择题错题 - 直接接收API返回的数据
     const prompts = await findpromptC(user_id, status)
     promptOptions.value = prompts
    const choiceRes = await choiceQ(user_id, status)
    choiceQuestions.value = choiceRes // 直接赋值，不需要.value

    // 获取填空题错题
    const answerRes = await answerQ(user_id, status)
    answerQuestions.value = answerRes // 直接赋值，不需要.value

    console.log('选择题:', choiceQuestions.value)
    console.log('填空题:', answerQuestions.value)
  } catch (error) {
    console.error('获取错题失败:', error)
    ElMessage.error('获取错题失败，请稍后重试')
  }
}
const searchByPrompt = async(tabName) => {
  if (!selectedPrompt.value) {
    ElMessage.warning('请选择或输入prompt')
    return
  }
// try {
//     if (tabName === 'choice') {
//       const prompt = selectedPrompt
//       choiceQuestions.value = await findchoicequestionprompt(prompt)
//     } else if (tabName === 'answer') {
//       const prompt = selectedPrompt
//       choiceQuestions.value = await findanswerquestionprompt(prompt)
//     }
//     // selectedPrompt.value = '' // 清空当前选择的prompt
//   }catch (error) {
//     ElMessage.error('获取列表失败')
//   }
}
const closePanel = async() => {
   visiblePanel.value = false
   activeTab.value='choice'
}
const deletechoice = async (question) => {
  try {
    await deleteMyWChoiceQ(question.id);
    ElMessage.success('删除成功');

    // 重新加载选择题数据
    const user_id = userStore.user.id;
    const choiceRes = await choiceQ(user_id, status);
    choiceQuestions.value = choiceRes;
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败，请稍后重试');
  }
}

const deletanswer = async (question) => {
  try {
    await deleteMyWAnswerQ(question.id);
    ElMessage.success('删除成功');

    // 重新加载填空题数据
    const user_id = userStore.user.id;
    const answerRes = await answerQ(user_id, status);
    answerQuestions.value = answerRes;
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败，请稍后重试');
  }
}
const handleTabChange = async (tabName) => {
   const user_id=userStore.user.id
  try {
    if (tabName === 'choice') {
      const prompts = await findpromptC(user_id, status)
      promptOptions.value = prompts
    } else if (tabName === 'answer') {
      const prompts = await findpromptA(user_id, status)
      promptOptions.value = prompts
    }
    selectedPrompt.value = '' // 清空当前选择的prompt
  } catch (error) {
    console.error('获取prompt列表失败:', error)
    ElMessage.error('获取prompt列表失败')
  }
}
</script>

<style scoped>
.exercise-btn {
  white-space: nowrap;
  padding: 5px 8px;
  background: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.exercise-btn:hover {
  background: #409EFF;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 5px;
}

.question-list {
  max-height: 500px;
  overflow-y: auto;
  padding: 10px;
}

.question-item {
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 8px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.question-header {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.question-index {
  margin-right: 8px;
  color: #409EFF;
}

.question-options {
  margin: 10px 0 10px 20px;
  color: #555;
}

.question-options div {
  margin-bottom: 5px;
}

.question-answer {
  margin: 10px 0;
  padding: 8px;
  background-color: #e8f4ff;
  border-radius: 4px;
  color: #409EFF;
  font-weight: bold;
}

.question-actions {
  margin-top: 10px;
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 50px 0;
  font-size: 16px;
}
.search-container {
  display: flex;
  margin-bottom: 20px;
  justify-content: flex-end;
}

.prompt-select {
  width: 800px;
  margin-right: 10px;
}

.search-btn {
  margin-left: 10px;
}
</style>
